//
//  AnnouncementViewController.m
//  DaDaBao
//
//  Created by User on 15/8/18.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "AnnouncementViewController.h"
#import "AnnouncementModel.h"
#import "AnnouncementDetailViewController.h"

@interface AnnouncementViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *listTableView;

@property (nonatomic, strong) NSMutableArray *listDataArray;

@property(nonatomic,strong) UIButton *noDataBt;

@property(nonatomic,strong)UIButton *tipBt;

@property (nonatomic, assign) int idx;

@property (nonatomic, assign) int n;

@end

@implementation AnnouncementViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    
}
- (void)getHttpData
{
    _n++;
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    
    _noDataBt.hidden = TRUE;
    _tipBt.hidden = TRUE;
   
    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1] };
    [AppGlobalClass PostDataWithNSstring:ANNOUNCEMENT_LIST_URL withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            if(_idx == 0)
            {
                [_listDataArray removeAllObjects];
            }
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray objectAtIndex:0];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                   AnnouncementModel *model = [[AnnouncementModel alloc]initWithDictionary:[listArray objectAtIndex:i]];

                    [_listDataArray addObject:model];
                }
                
                _idx++;
                [_listTableView.header endRefreshing];
                [_listTableView.footer setState:MJRefreshStateIdle];
                [_listTableView.footer endRefreshing];


                if(listArray.count < 10)
                {
                    [self.listTableView.footer noticeNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        self.listTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                    }
                }
                [self.listTableView reloadData];
                
            }
            else
            {
                if (self.listDataArray.count==0) {
                    _noDataBt.hidden = FALSE;

                }

                [self.listTableView.footer noticeNoMoreData];
            }
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } failure:^(NSError *error){
        
        [self.listDataArray removeAllObjects];
        [self.listTableView reloadData];
        
        _noDataBt.hidden = FALSE;
        
        [_listTableView.header endRefreshing];
        [_listTableView.footer setState:MJRefreshStateIdle];
        [_listTableView.footer endRefreshing];
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
} networkerror:^(NSString *networkerror){
    [self.listDataArray removeAllObjects];
    [self.listTableView reloadData];
    
    _tipBt.hidden = FALSE;
    
    [_listTableView.header endRefreshing];
    [_listTableView.footer setState:MJRefreshStateIdle];
    [_listTableView.footer endRefreshing];
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    if (!_listDataArray) {
        _listDataArray = [[NSMutableArray alloc]init];
    }
    [self  createUI];
}
-(void)createUI
{
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"服务公告"];
    [self.view addSubview:topView];
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    [self.view addSubview:self.listTableView];
    
    [self.listTableView addSubview:self.tipBt];
    [self.listTableView addSubview:self.noDataBt];
}

//没网提示
-(UIButton *)tipBt
{
    if (!_tipBt) {
        _tipBt = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_tipBt setBackgroundImage:[UIImage imageNamed:@"network_error"] forState:UIControlStateNormal];
        [_tipBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        _tipBt.hidden = TRUE;
    }
    return _tipBt;
}

- (UIButton *)noDataBt
{
    if (!_noDataBt) {
        _noDataBt = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_noDataBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataBt setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        _noDataBt.hidden = TRUE;
    }
    return _noDataBt;
}

- (void)buttonAgainTapped:(id)sender
{
    [_listTableView.header beginRefreshing];
}

-(UITableView *)listTableView
{
    if (!_listTableView) {
        if ( _listTableView == nil)
        {
            _listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 70.0f, SCREEN_WIDTH, SCREEN_HEIGHT - 74.0f) style:UITableViewStylePlain];
            
            __weak __typeof(self) weakSelf = self;
            
            // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
            _listTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                [weakSelf refreshTheProjectTableView];
            }];
            
            // 马上进入刷新状态
            [_listTableView.header beginRefreshing];
            _listTableView.delegate=self;
            _listTableView.dataSource=self;
            _listTableView.sectionHeaderHeight = 0.0f;
            _listTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];//设置当数据不多的时候，下面无cell
        }
    }
    return _listTableView;
}

#pragma mark- tableviewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        
        UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(20.0f, 10.0f, SCREEN_WIDTH - 190.0f, 20.0f)];
        titleLab.backgroundColor = [UIColor clearColor];
        titleLab.font = [UIFont systemFontOfSize:16.0f];
        [titleLab setTag:100];
        [cell.contentView addSubview:titleLab];
        
        UILabel *timeLab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 160.0f, 10.0f, 140.0f, 20.0f)];
        timeLab.textAlignment = NSTextAlignmentRight;
        timeLab.font = [UIFont systemFontOfSize:15.0f];
        timeLab.textColor = [UIColor lightGrayColor];
        [timeLab setTag:101];
        [cell.contentView addSubview:timeLab];
        
        UILabel *profileLab = [[UILabel alloc]initWithFrame:CGRectMake(20.0f, 35.0f, SCREEN_WIDTH - 40.0f, 0.0f)];
        profileLab.numberOfLines = 0;
        profileLab.backgroundColor = [UIColor clearColor];
        profileLab.font = [UIFont systemFontOfSize:15.0f];
        profileLab.textColor = [UIColor lightGrayColor];
        [profileLab setTag:102];
        [cell.contentView addSubview:profileLab];
    }
    
    AnnouncementModel *announcementModel = [_listDataArray objectAtIndex:indexPath.row];
    
    UILabel *modelTitleLab = (UILabel *)[cell.contentView viewWithTag:100];
    modelTitleLab.text = announcementModel.title;
    
    UILabel *modelTimeLab = (UILabel *)[cell.contentView viewWithTag:101];
    modelTimeLab.text = announcementModel.publishTime;
    
    UILabel *modelProfileLab = (UILabel *)[cell.contentView viewWithTag:102];
    modelProfileLab.frame = CGRectMake(20.0f, 35.0f, SCREEN_WIDTH - 40.0f, [UILabel height:announcementModel.profile widthOfFatherView:SCREEN_WIDTH - 40.0f textFont:[UIFont systemFontOfSize:15.0f]]);
    modelProfileLab.text = announcementModel.profile;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnnouncementModel *announcementModel = [_listDataArray objectAtIndex:indexPath.row];
    return [UILabel height:announcementModel.profile widthOfFatherView:SCREEN_WIDTH - 40.0f textFont:[UIFont systemFontOfSize:15.0f]] + 40.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    AnnouncementModel *announcementModel = [_listDataArray objectAtIndex:indexPath.row];
    AnnouncementDetailViewController *announcementDeViewCon = [[AnnouncementDetailViewController alloc]initWithModel:announcementModel];
    [self.navigationController pushViewController:announcementDeViewCon animated:TRUE];
}

//刷新表
-(void)refreshTheProjectTableView
{
    _idx = 0;
    _n = 0;
    [self getHttpData];
}

//加载更多数据
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}

- (void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
